import sqlite3
from typing import List, Dict, Any
from scripts.config_reader import ConfigReader


class SimpleDB:
    def __init__(self, cursor):
        self.cursor = cursor
        self.conn = cursor.connection

    def execute(self, sql, params=(), commit=False):
        """执行SQL语句"""
        self.cursor.execute(sql, params)
        if commit:
            self.conn.commit()
        return self.cursor

    def insert(self, table, data: Dict[str, Any]):
        """插入单条数据"""
        cols = ','.join(data.keys())
        vals = ','.join(['?'] * len(data))
        sql = f"INSERT INTO {table} ({cols}) VALUES ({vals})"
        self.execute(sql, tuple(data.values()), commit=True)

    def select(self, table, where="", params=()) -> List[Dict]:
        """查询数据"""
        sql = f"SELECT * FROM {table}"
        if where:
            sql += f" WHERE {where}"
        self.cursor.execute(sql, params)
        return [row for row in self.cursor.fetchall()]

    def update(self, table, data: Dict[str, Any], where, params=()) -> int:
        """更新数据"""
        sets = ','.join([f"{k}=?" for k in data])
        sql = f"UPDATE {table} SET {sets} WHERE {where}"
        self.execute(sql, all_params, commit=True)
        return self.cursor.rowcount

    def delete(self, table, where, params=()) -> int:
        """删除数据"""
        sql = f"DELETE FROM {table} WHERE {where}"
        self.execute(sql, params, commit=True)
        return self.cursor.rowcount

    def close(self):
        """关闭连接"""
        self.conn.close()
if __name__ == '__main__':
    config = ConfigReader()
